package com.wiwf.model.magicapi.redis.starter;

import com.wiwf.model.magicapi.redis.module.RedisModule;
import com.wiwf.model.magicapi.redis.service.RedisResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.model.Plugin;
import org.ssssssss.magicapi.core.resource.Resource;

@Configuration
public class MagicRedisConfiguration implements MagicPluginConfiguration {
    private final MagicAPIProperties properties;

    public MagicRedisConfiguration(MagicAPIProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(
            prefix = "magic-api",
            name = {"resource.type"},
            havingValue = "redis"
    )
    public Resource magicRedisResource(RedisConnectionFactory connectionFactory) {
        org.ssssssss.magicapi.core.config.Resource resource = this.properties.getResource();
        return new RedisResource(new StringRedisTemplate(connectionFactory), resource.getPrefix(), resource.isReadonly());
    }

    @Bean
    public RedisModule redisFunctions(RedisConnectionFactory connectionFactory) {
        return new RedisModule(connectionFactory);
    }

    public Plugin plugin() {
        return new Plugin("Redis");
    }
}
